package dao

import (
	"fmt"
	"strconv"
	"strings"
	"time"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/helper/resphelper"
	"yundian/internel/app/helper/resphelper/placeresp"
	"yundian/internel/app/models/agentincome"
	"yundian/internel/app/models/cashlog"
	"yundian/internel/app/models/ordersstatistics"
	"yundian/internel/app/models/placeincome"
	"yundian/internel/app/models/users"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	"yundian/internel/pkg/utils"
)

// GetUserTotalOrderMembers 独立用户数
func (d *OrderDao) GetUserTotalOrderMembers(userId int, inDay string) *dingo.ErrorWrap {
	count := int64(0)

	dayWhere := "AND our.end_date>?"
	if inDay != "" {
		dayWhere = "AND our.end_date=?"
	} else {
		inDay = "1970-01-01"
	}

	sql := fmt.Sprintf(`SELECT COUNT(1) FROM (SELECT openid FROM orders o LEFT JOIN orders_user_relevancy our 
	ON o.id=our.id WHERE our.user_id=? %s AND o.state=? AND o.is_draw<>? GROUP BY o.openid)o1`, dayWhere)
	db := global.Orm.Raw(sql, userId, inDay, helper.TypeNumOrderStatusFinish, helper.TypeNumCommonStatusTrue).Find(&count)
	return dingo.ErrorIf(db.Error, count)
}

// GetUserTotalDividendsAll 获取用户收益总统计
func (d *OrderDao) GetUserTotalDividendsAll(userId int, inDay string) *dingo.ErrorWrap {
	amount := int64(0)
	db := global.Orm.Table("dividends_log").Select("IFNULL(SUM(money),0)")
	db.Where("user_id=?", userId)

	if inDay != "" {
		db.Where("end_date=?", inDay)
	}

	db.Find(&amount)
	return dingo.ErrorIf(db.Error, amount)
}

// GetUserTotalDividendsMonthAll 获取用户收益总统计
func (d *OrderDao) GetUserTotalDividendsMonthAll(userId int, inMonth string) *dingo.ErrorWrap {
	amount := int64(0)
	db := global.Orm.Table("dividends_log").Select("IFNULL(SUM(money),0)")
	db.Where("user_id=?", userId)

	if inMonth != "" {
		db.Where("end_month=?", inMonth)
	}

	db.Find(&amount)
	return dingo.ErrorIf(db.Error, amount)
}

// GetUserTotalOrderAll 获取用户订单总统计
func (d *OrderDao) GetUserTotalOrderAll(userId int, inDay string) *dingo.ErrorWrap {
	dbInfo := &request.TotalOrderAllRes{}
	db := global.Orm.Table("orders o").Select("COUNT(1) num, SUM(o.settlement_money) amount")
	db.Joins("LEFT JOIN orders_user_relevancy our ON o.id=our.id")
	db.Where("our.user_id=? AND o.state=? AND o.is_draw<>?", userId, helper.TypeNumOrderStatusFinish, helper.TypeNumCommonStatusTrue)

	if inDay != "" {
		db.Where("our.end_date=?", inDay)
	}

	db.Find(&dbInfo)
	return dingo.ErrorIf(db.Error, dbInfo)
}

// 获取总金额
func (d *OrderDao) GetTotalMoney() *dingo.ErrorWrap {
	total := &struct {
		Total int64
		Count int64
	}{}
	sql := `SELECT IFNULL(SUM(settlement_money),0) as total,count(1) as count FROM orders WHERE state = 5`
	db := global.Orm.Raw(sql).Find(&total)
	return dingo.ErrorIf(db.Error, total.Total, total.Count)
}

// 获取抽单总金额
//func (d *OrderDao) GetTakeTotalMoney() *dingo.ErrorWrap {
//	total := &struct {
//		Total int64
//		Count int64
//	}{}
//	sql := `SELECT SUM(settlement_money) as total,count(id) as count FROM orders_take WHERE state = 5`
//	db := global.Orm.Raw(sql).Find(&total)
//	return dingo.ErrorIf(db.Error, total.Total, total.Count)
//}

// 获取用户销售额/支付笔数 总数据
func (d *OrderDao) GetUserOrderMoneyAndCountAll(userId int, isAdmin, isDraw uint8) *dingo.ErrorWrap {
	var data struct {
		Money int64
		Total int64
	}

	db := global.Orm.Debug().Table("orders o").Select("SUM(o.settlement_money)money,COUNT(1) total")
	db.Joins("LEFT JOIN orders_user_relevancy our ON o.trade_no=our.trade_no")
	db.Where("our.user_id=? AND o.state=?", userId, helper.TypeNumOrderStatusFinish)

	if isAdmin != helper.TypeNumIsAdminOperator {
		//if isDraw != helper.TypeNumIsDrawOpen {
		//	db.Where("o.is_draw<>? or o.agent_user_id=?", helper.TypeNumIsDrawOpen, userId)
		//} else {
		//	db.Where("o.is_draw<>? or (o.is_draw=? and o.agent_user_id=?)", helper.TypeNumIsDrawOpen, helper.TypeNumIsDrawOpen, userId)
		//}
		db.Where("o.is_draw<>? or (o.is_draw=? and o.agent_user_id=?)", helper.TypeNumIsDrawOpen, helper.TypeNumIsDrawOpen, userId)
		db.Where("o.is_tianhai = 0")
	}

	db.Find(&data)
	return dingo.ErrorIf(db.Error, []int64{data.Money, data.Total})
}

// 获取用户销售额/支付笔数 某一天数据
func (d *OrderDao) GetUserOrderMoneyAndCountDay(userId int, isAdmin, isDraw uint8, day int) *dingo.ErrorWrap {
	var data struct {
		Money int64
		Total int64
	}

	db := global.Orm.Debug().Table("orders o").Select("SUM(o.settlement_money)money,COUNT(1) total")
	db.Joins("LEFT JOIN orders_user_relevancy our ON o.trade_no=our.trade_no")
	db.Where("our.user_id=? AND o.state=?", userId, helper.TypeNumOrderStatusFinish)
	db.Where("our.end_date=DATE_SUB(CURDATE(), INTERVAL ? DAY)", day)

	if isAdmin != helper.TypeNumIsAdminOperator {
		//if isDraw != helper.TypeNumIsDrawOpen {
		//	db.Where("o.is_draw<>? or o.agent_user_id=?", helper.TypeNumIsDrawOpen, userId)
		//} else {
		//	db.Where("o.is_draw<>? or (o.is_draw=? and o.agent_user_id=?)", helper.TypeNumIsDrawOpen, helper.TypeNumIsDrawOpen, userId)
		//}
		db.Where("o.is_draw<>? or (o.is_draw=? and o.agent_user_id=?)", helper.TypeNumIsDrawOpen, helper.TypeNumIsDrawOpen, userId)
		db.Where("o.is_tianhai = 0")
	}

	db.Find(&data)
	return dingo.ErrorIf(db.Error, []int64{data.Money, data.Total})
}

// 获取用户销售额/支付笔数 某一周数据
func (d *OrderDao) GetUserOrderMoneyAndCountWeek(userId int, isAdmin, isDraw uint8, week int) *dingo.ErrorWrap {
	var data struct {
		Money int64
		Total int64
	}

	startWeek := 7 + (week * 7) + 1
	endWeek := (week * 7) + 1
	db := global.Orm.Debug().Table("orders o").Select("SUM(o.settlement_money)money,COUNT(1) total")
	db.Joins("LEFT JOIN orders_user_relevancy our ON o.trade_no=our.trade_no")
	db.Where("our.user_id=? AND o.state=?", userId, helper.TypeNumOrderStatusFinish)
	db.Where("our.end_date>=DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE())+? DAY)", startWeek)
	db.Where("our.end_date<DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE())+? DAY)", endWeek)

	if isAdmin != helper.TypeNumIsAdminOperator {
		//if isDraw != helper.TypeNumIsDrawOpen {
		//	db.Where("o.is_draw<>? or o.agent_user_id=?", helper.TypeNumIsDrawOpen, userId)
		//} else {
		//	db.Where("o.is_draw<>? or (o.is_draw=? and o.agent_user_id=?)", helper.TypeNumIsDrawOpen, helper.TypeNumIsDrawOpen, userId)
		//}
		db.Where("o.is_draw<>? or (o.is_draw=? and o.agent_user_id=?)", helper.TypeNumIsDrawOpen, helper.TypeNumIsDrawOpen, userId)
		db.Where("o.is_tianhai = 0")
	}

	db.Find(&data)
	return dingo.ErrorIf(db.Error, []int64{data.Money, data.Total})
}

// 获取转帐提现金额
//func (d *OrderDao) GetCashLogByUserId(userId int) *dingo.ErrorWrap {
//	var total int64
//	//	sql := `select IFNULL(SUM(transfer_money),0) as total from
//	//cash_log WHERE user_id = ? and state = 2 and create_at > unix_timestamp('2021-04-08 18:00:00')`
//	sql := `select IFNULL(SUM(transfer_money),0) as total from
//cash_log WHERE user_id = ? and state = 2 and is_tianhai = 0`
//	db := global.Orm.Debug().Raw(sql, userId).Find(&total)
//	return dingo.ErrorIf(db.Error, total)
//}
// 获取转帐提现金额
func (d *OrderDao) GetCashLogByUserId(userId int) *dingo.ErrorWrap {
	var total int64
	//	sql := `select IFNULL(SUM(transfer_money),0) as total from
	//cash_log WHERE user_id = ? and state = 2 and create_at > unix_timestamp('2021-04-08 18:00:00')`
	sql := `select IFNULL(SUM(money),0) as total from 
cash_log WHERE user_id = ? and state = 2 and is_tianhai = 0`
	db := global.Orm.Debug().Raw(sql, userId).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

func (d *OrderDao) GetCashLogByInfo(userId int) *dingo.ErrorWrap {
	cashLogModel := cashlog.CashLogModel{}
	sql := `select * from 
cash_log WHERE user_id = ? and state = 1 and is_tianhai = 0`
	db := global.Orm.Debug().Raw(sql, userId).Find(&cashLogModel)
	return dingo.ErrorIf(db.Error, cashLogModel)
}

func (d *OrderDao) GetCashLogToMaxMoney(userId int, isPlace uint8) *dingo.ErrorWrap {
	var list []int64
	isType := 1
	if isPlace == helper.TypeNumIsPlaceAgent || isPlace == helper.TypeNumIsPlaceEmployed {
		isType = 2
	}

	sql := `SELECT IFNULL(SUM(money),0) money FROM cash_log cl WHERE cl.user_id=? AND cl.state=2
	AND DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d')=DATE_FORMAT(NOW(),'%Y-%m-%d') UNION
	SELECT day_max_money money FROM withdrawal_setting WHERE type=?`
	db := global.Orm.Debug().Raw(sql, userId, isType).Find(&list)
	return dingo.ErrorIf(db.Error, list)
}

// 获取用户当天提现金额
func (d *OrderDao) GetTodayCashLogByUserId(userId int) *dingo.ErrorWrap {
	var total int64
	sql := `select IFNULL(SUM(transfer_money),0) as total from 
cash_log WHERE user_id = ? and state = 2 and 
DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d')=DATE_FORMAT(CURRENT_DATE(), '%Y-%m-%d')`
	db := global.Orm.Debug().Raw(sql, userId).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

func (d *OrderDao) GetToMonthCashLogByUserId(userId int) *dingo.ErrorWrap {
	var total int64
	sql := `select IFNULL(SUM(transfer_money),0) as total from 
cash_log WHERE user_id = ? and state = 2 and 
PERIOD_DIFF( date_format( now( ), '%Y%m' ), date_format( DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d'), '%Y%m' ) ) = 1`
	db := global.Orm.Debug().Raw(sql, userId).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

// 获取用户分红金额
func (d *OrderDao) GetDividendsMoneyByUserId(userId int) *dingo.ErrorWrap {
	var total int64
	//sql := "SELECT IFNULL(SUM(money),0) as total FROM dividends_log WHERE user_id = ?  and create_at > unix_timestamp('2021-04-02 03:00:00')"
	sql := "SELECT IFNULL(SUM(money),0) as total FROM dividends_log WHERE user_id = ?  and is_tianhai = 0"
	db := global.Orm.Debug().Raw(sql, userId).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

// 判断用户是否分红
func (d *OrderDao) CountDividendsLogsByTradeNo(tradeNo string, userId int) *dingo.ErrorWrap {
	var count int64
	sql := "SELECT count(*) FROM dividends_log WHERE trade_no = ? and user_id = ?  and is_tianhai = 0"
	db := global.Orm.Debug().Raw(sql, tradeNo, userId).Find(&count)
	return dingo.ErrorIf(db.Error, count)
}

// 获取用户当天的分红金额
func (d *OrderDao) GetTodayDividendsMoneyByUserId(userId int) *dingo.ErrorWrap {
	var total int64
	sql := `SELECT IFNULL(SUM(money),0) as total FROM dividends_log WHERE user_id = ? 
	and end_date=DATE_FORMAT(CURRENT_DATE(), '%Y-%m-%d')`
	db := global.Orm.Debug().Raw(sql, userId).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

func (d *OrderDao) GetToMonthDividendsMoneyByUserId(userId int) *dingo.ErrorWrap {
	var total int64
	sql := `SELECT IFNULL(SUM(money),0) as total FROM dividends_log WHERE user_id = ? 
and PERIOD_DIFF( date_format( now( ), '%Y%m' ), date_format( DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d'), '%Y%m' ) ) = 1 `
	db := global.Orm.Debug().Raw(sql, userId).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

// 获取代理商抽单总收益
func (d *OrderDao) GetTakeTotalMoneyByUserId(userId int) *dingo.ErrorWrap {
	var total int64
	sql := `SELECT IFNULL(SUM(settlement_money),0) as total FROM orders 
WHERE is_draw = 1 and state = 5 and is_tianhai = 0 and agent_user_id = ?`
	db := global.Orm.Debug().Raw(sql, userId).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

// 当天抽单总收益
func (d *OrderDao) GetTodayDrawMoneyByUserId(userId int) *dingo.ErrorWrap {
	var total int64
	sql := `SELECT IFNULL(SUM(settlement_money),0) as total FROM orders WHERE is_draw = 1 and state = 5 and is_tianhai = 0 and agent_user_id = ? 
and DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d')=DATE_FORMAT(CURRENT_DATE(), '%Y-%m-%d')`
	db := global.Orm.Debug().Raw(sql, userId).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

// 获取抽单总金额
func (d *OrderDao) GetTakeTotalMoney() *dingo.ErrorWrap {
	var total int64
	//sql := `SELECT SUM(settlement_money) as total FROM orders_take WHERE state = 5 and user_id = ?`
	sql := `SELECT IFNULL(SUM(settlement_money),0) as total FROM orders 
WHERE is_draw = 1 and state = 5`
	db := global.Orm.Debug().Raw(sql).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

// 获取用户的抽单总金额
//func (d *OrderDao) GetTakeTotalMoneyByUserId(userId int, isAdmin uint8) *dingo.ErrorWrap {
//	var total int64
//
//	db := global.Orm.Table("orders").
//		Select("IFNULL(SUM(settlement_money),0) as total").
//		Where("is_draw = 1 and state = 5")
//
//	if isAdmin == 3 { // 代理商
//		// 获取该用户下所有下级
//		pidArr := []int{userId}
//		userIdArr := make([]int, 0)
//		isRecursive := true
//		// 递归 无限查询下级
//		for isRecursive {
//			tempUserIdArr := NewUserDao().GetUserIdByPid(pidArr).Unwrap().([]int)
//
//			if len(tempUserIdArr) == 0 {
//				isRecursive = false
//			} else {
//				userIdArr = append(userIdArr, tempUserIdArr...)
//				pidArr = tempUserIdArr
//				//log.Println("当前pid数组：",pidArr)
//				//log.Println("当前userIdArr数组：",userIdArr)
//			}
//		}
//
//		db.Where("user_id in ?", userIdArr)
//	}
//
//	// 运营商抽单数 = 全部抽单数-被代理商抽单数
//	if isAdmin == 2 { // 运营商
//		// 所有代理商
//		agentUserList := NewUserDao().GetAllAgentUserList("").Unwrap().([]*users.UserModel)
//		pidArr := make([]int, 0)
//		for _, agentUser := range agentUserList {
//			// 提到代理商用户ID 数组
//			pidArr = append(pidArr, []int{agentUser.ID}...)
//		}
//
//		// 获取该用户下所有下级
//		userIdArr := make([]int, 0)
//		isRecursive := true
//		// 递归 无限查询下级
//		for isRecursive {
//			tempUserIdArr := NewUserDao().GetUserIdByPid(pidArr).Unwrap().([]int)
//
//			if len(tempUserIdArr) == 0 {
//				isRecursive = false
//			} else {
//				userIdArr = append(userIdArr, tempUserIdArr...)
//				pidArr = tempUserIdArr
//				//log.Println("当前pid数组：",pidArr)
//				//log.Println("当前userIdArr数组：",userIdArr)
//			}
//		}
//
//		// 运营商抽单总数要扣除代理商的
//		db.Where("user_id not in ?", userIdArr)
//	}
//
//	//sql := `SELECT IFNULL(SUM(settlement_money),0) as total FROM orders
//	//		WHERE is_draw = 1 and state = 5 and parent_id = ?`
//
//	db.Find(&total)
//
//	return dingo.ErrorIf(db.Error, total)
//}

// 获取用户当天的抽单总金额
func (d *OrderDao) GetTodayTakeTotalMoneyByUserId(userId int, isAdmin uint8) *dingo.ErrorWrap {

	//	sql := `SELECT IFNULL(SUM(settlement_money),0) as total FROM orders
	//WHERE is_draw = 1 and state = 5 and parent_id = ? and
	//DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d')=DATE_FORMAT(CURRENT_DATE(), '%Y-%m-%d')`
	var total int64
	db := global.Orm.Table("orders").
		Select("IFNULL(SUM(settlement_money),0) as total").
		Where("is_draw = 1 and state = 5").
		Where("DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d')=DATE_FORMAT(CURRENT_DATE(), '%Y-%m-%d')")

	if isAdmin == 3 { // 代理商
		// 获取该用户下所有下级
		pidArr := []int{userId}
		userIdArr := make([]int, 0)
		isRecursive := true
		// 递归 无限查询下级
		for isRecursive {
			tempUserIdArr := NewUserDao().GetUserIdByPid(pidArr).Unwrap().([]int)

			if len(tempUserIdArr) == 0 {
				isRecursive = false
			} else {
				userIdArr = append(userIdArr, tempUserIdArr...)
				pidArr = tempUserIdArr
				//log.Println("当前pid数组：",pidArr)
				//log.Println("当前userIdArr数组：",userIdArr)
			}
		}

		db.Where("user_id in ?", userIdArr)
	}

	// 运营商抽单数 = 全部抽单数-被代理商抽单数
	if isAdmin == 2 { // 运营商
		// 所有代理商
		agentUserList := NewUserDao().GetAllAgentUserList("").Unwrap().([]*users.UserModel)
		pidArr := make([]int, 0)
		for _, agentUser := range agentUserList {
			// 提到代理商用户ID 数组
			pidArr = append(pidArr, []int{agentUser.ID}...)
		}

		// 获取该用户下所有下级
		userIdArr := make([]int, 0)
		//isRecursive := true
		// 递归 无限查询下级
		//for isRecursive {
		//	tempUserIdArr := NewUserDao().GetUserIdByPid(pidArr).Unwrap().([]int)
		//
		//	if len(tempUserIdArr) == 0 {
		//		isRecursive = false
		//	} else {
		//		userIdArr = append(userIdArr, tempUserIdArr...)
		//		pidArr = tempUserIdArr
		//		//log.Println("当前pid数组：",pidArr)
		//		//log.Println("当前userIdArr数组：",userIdArr)
		//	}
		//}
		tempUserIdArr := NewUserDao().GetUserIdByPid(pidArr).Unwrap().([]int)
		if len(tempUserIdArr) == 0 {
			userIdArr = append(userIdArr, tempUserIdArr...)
			pidArr = tempUserIdArr
		}

		// 运营商抽单总数要扣除代理商的
		db.Where("user_id not in ?", userIdArr)
	}

	db.Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

// 获取用户当天的抽单总金额
func (d *OrderDao) GetToMonthTakeTotalMoneyByUserId(userId int, isAdmin uint8) *dingo.ErrorWrap {

	//	sql := `SELECT IFNULL(SUM(settlement_money),0) as total FROM orders
	//WHERE is_draw = 1 and state = 5 and parent_id = ? and
	//DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d')=DATE_FORMAT(CURRENT_DATE(), '%Y-%m-%d')`
	var total int64
	db := global.Orm.Table("orders").
		Select("IFNULL(SUM(settlement_money),0) as total").
		Where("is_draw = 1 and state = 5").
		Where("PERIOD_DIFF( date_format( now( ), '%Y%m' ), date_format( DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d'), '%Y%m' ) ) = 1")

	if isAdmin == 3 { // 代理商
		// 获取该用户下所有下级
		userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
		db.Where("user_id in ?", userIdArr)
	}

	// 运营商抽单数 = 全部抽单数-被代理商抽单数
	if isAdmin == 2 { // 运营商
		// 所有代理商
		userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
		// 运营商抽单总数要扣除代理商的
		db.Where("user_id not in ?", userIdArr)
	}

	db.Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

// 获取某一天的销售额
func (d *OrderDao) GetTodayTotalMoney(t string) *dingo.ErrorWrap {
	var total int64
	//	sql := `SELECT SUM(settlement_money) as total from (SELECT money,settlement_money,DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') AS days, trade_no, place_name, user_name ,place_id, user_id
	//FROM orders WHERE DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = DATE_FORMAT(CURRENT_DATE(), '%Y-%m-%d') GROUP BY create_at desc) as a`
	//	sql := `SELECT IFNULL(SUM(settlement_money),0) as total from
	//(SELECT money,settlement_money FROM orders WHERE DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = ? GROUP BY create_at desc) as a`
	sql := `SELECT IFNULL( SUM( settlement_money ), 0 ) AS total FROM orders 
			WHERE state = 5 and DATE_FORMAT( FROM_UNIXTIME( end_at ), '%Y-%m-%d' ) = ?`

	db := global.Orm.Raw(sql, t).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

// 获取某一天的销售订单笔数
func (d *OrderDao) GetTodayOrderCount(t string) *dingo.ErrorWrap {
	var count int64
	sql := `SELECT count(*) as count from 
(SELECT money,settlement_money FROM orders WHERE DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = ? GROUP BY end_at desc) as a`
	db := global.Orm.Raw(sql, t).Find(&count)
	return dingo.ErrorIf(db.Error, count)
}

// 获取周销售额
func (d *OrderDao) GetWeekTotalMoney(i int) *dingo.ErrorWrap {
	var total int64
	//	sql := `SELECT IFNULL(SUM(settlement_money),0) as total from
	//(SELECT money,settlement_money,DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') AS days,
	//YEARWEEK(DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d'),1) as weeks FROM orders WHERE
	//YEARWEEK(DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d'),1) = YEARWEEK(now(),1)-?) as a`

	// modify by boyka on 20210407 将上面SQL简化，如果有问题及时联系
	sql := `SELECT IFNULL(SUM(settlement_money),0) as total FROM orders WHERE 
			YEARWEEK(DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d'),1) = YEARWEEK(now(),1)-?`

	db := global.Orm.Raw(sql, i).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

// 获取近几天的交易笔数
func (d *OrderDao) GetLastDayOrderCount(i int) *dingo.ErrorWrap {
	var lst []*resphelper.ChartListResp
	sql := `SELECT count(1) as y,DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') AS x
FROM orders WHERE state = 5 and
date_sub(curdate(), interval ? day) <= DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d')
GROUP BY DATE_FORMAT(FROM_UNIXTIME(end_at), '%Y-%m-%d') asc`
	db := global.Orm.Raw(sql, i).Find(&lst)
	return dingo.ErrorIf(db.Error, lst)
}

// 获取近几天的交易金额
func (d *OrderDao) GetLastDayOrderTotal(i int) *dingo.ErrorWrap {
	var lst []*resphelper.ChartListResp
	sql := `SELECT IFNULL(SUM(settlement_money),0) as total,
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') AS day
FROM orders WHERE state = 5 and is_tianhai = 0 and 
date_sub(curdate(), interval ? day) <= DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') 
GROUP BY DATE_FORMAT(FROM_UNIXTIME(end_at), '%Y-%m-%d') asc`
	db := global.Orm.Raw(sql, i).Find(&lst)
	return dingo.ErrorIf(db.Error, lst)
}

// 获取用户近十天的抽单金额
func (d *OrderDao) GetLastDayDrawTotalByParentId(userId int) *dingo.ErrorWrap {
	var lst []*resphelper.ChartResp
	sql := `SELECT IFNULL(SUM(settlement_money),0) as y,DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') AS x
FROM orders WHERE agent_user_id = ? and is_draw = 1 and state = 5 and 
date_sub(curdate(), interval 10 day) <= DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') 
GROUP BY DATE_FORMAT(FROM_UNIXTIME(end_at), '%Y-%m-%d') asc`
	db := global.Orm.Debug().Debug().Raw(sql, userId).Find(&lst)
	return dingo.ErrorIf(db.Error, lst)
}

// 获取用户近十天的分红金额
func (d *OrderDao) GetLastDayDividendsTotalByParentId(userId int) *dingo.ErrorWrap {
	var lst []*resphelper.ChartResp
	sql := `SELECT IFNULL(SUM(money),0) as y,DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') AS x
FROM dividends_log WHERE user_id = ? and 
date_sub(curdate(), interval 10 day) <= DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') 
GROUP BY DATE_FORMAT(FROM_UNIXTIME(create_at), '%Y-%m-%d') asc`
	db := global.Orm.Debug().Raw(sql, userId).Find(&lst)
	return dingo.ErrorIf(db.Error, lst)
}

// 获取设备的销售统计
func (d *OrderDao) GetDeviceSales(sharedMode, timeRange string, isAdmin uint8, userId int, isPlace uint8) *dingo.ErrorWrap {

	if sharedMode == "" {
		sharedMode = "pcl"
	}

	var lst []*resphelper.ChartListResp

	db := global.Orm.Debug().Table("orders o")
	db.Joins("LEFT JOIN orders_user_relevancy our ON o.trade_no=our.trade_no")
	db.Select("IFNULL( SUM( o.settlement_money ), 0 ) AS y,DATE_FORMAT( FROM_UNIXTIME( o.end_at ), '%Y-%m-%d' ) AS x ")
	db.Where("our.user_id=? AND o.state=?", userId, helper.TypeNumOrderStatusFinish)
	db.Where("o.shared_mode = ? ", sharedMode)
	db.Where("DATE_FORMAT( FROM_UNIXTIME( o.end_at ), '%Y-%m-%d' ) >= date_sub( curdate(), INTERVAL 31 DAY ) ")
	db.Where("DATE_FORMAT( FROM_UNIXTIME( o.end_at ), '%Y-%m-%d' ) <= date_sub( curdate(), INTERVAL 1 DAY )")

	if isAdmin != helper.TypeNumIsAdminOperator {
		db.Where("o.is_draw<>? or (o.is_draw=? and o.agent_user_id=?)", helper.TypeNumIsDrawOpen, helper.TypeNumIsDrawOpen, userId)
		db.Where("o.is_tianhai = 0")
	}

	db.Group("DATE_FORMAT( FROM_UNIXTIME( o.end_at ), '%Y-%m-%d' ) ASC").Find(&lst)
	return dingo.ErrorIf(db.Error, lst)
}

// 商户销售排行版
func (d *OrderDao) GetPlaceSalesRankList(sharedMode, timeRange string, limit int, isAdmin uint8, userId int, isPlace uint8) *dingo.ErrorWrap {

	if sharedMode == "" {
		sharedMode = "pcl"
	}

	if limit == 0 {
		limit = 10
	}

	var c []string
	if timeRange != "" {
		c = strings.Split(timeRange, ",")
	} else {
		c = []string{
			//time.Now().AddDate(0,0,-11).Format("2006-01-02"),
			//time.Now().AddDate(0,0,-1).Format("2006-01-02"),
			strconv.FormatInt(time.Now().AddDate(0, 0, -30).Unix(), 10),
			strconv.FormatInt(time.Now().AddDate(0, 0, -1).Unix(), 10),
		}
	}

	var lst []*placeresp.PlaceRankList
	db := global.Orm.Debug().Table("orders o").
		Select("IFNULL(SUM(o.settlement_money),0) as total, p.place_name, p.device_count").
		Joins("LEFT JOIN places p ON p.id = o.place_id").
		Where("o.is_draw = ?", 0).
		Where("o.shared_mode = ?", sharedMode).
		Where("o.end_at >= ?", c[0]).
		Where("o.end_at <= ?", c[1])

	if isAdmin > helper.TypeNumIsAdminStaff { //当前账号登录是代理商或是合伙人
		// 获取某个用户下的所有代理商用户ID
		//placeModelLst := NewPlaceDao().GetPlaceByparentId(userId).Unwrap().([]*placemodel.PlaceModel)
		//placeIdArr := make([]int, 0)
		////log.Println("placeModelLst 数组长度：", len(placeModelLst))
		//for _, placeModel := range placeModelLst {
		//	//fmt.Println("placeId: ",placeModel.Id)
		//	placeIdArr = append(placeIdArr, placeModel.Id)
		//}
		////log.Println("placeIdArr dao数组：", placeIdArr)
		//db.Where("o.place_id in ?", placeIdArr)
		userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
		db.Where("o.agent_user_id in ?", userIdArr)
	}

	if isAdmin == helper.TypeNumIsAdminBranch {
		childUserIds := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
		placesIdArr := NewUserDao().GetPlacesIds(userId, childUserIds).Unwrap().([]int)
		db.Where("o.place_id in ?", placesIdArr)
	}

	db.Group("o.place_id").Order("total desc")
	db.Limit(limit).Find(&lst)

	//	sql := `SELECT IFNULL(SUM(o.settlement_money),0) as total, p.place_name, p.device_count
	//FROM orders o LEFT JOIN places p ON p.id = o.place_id WHERE o.shared_mode = ? and o.create_at >= ?
	//and o.create_at <= ? GROUP BY o.place_id ORDER BY total desc limit ?`
	//	db := global.Orm.Raw(sql, sharedMode, c[0], c[1], limit).Find(&lst)
	return dingo.ErrorIf(db.Error, lst)
}

// 商户使用率列表
func (d *OrderDao) GetPlaceUsedRateList(param *request.OrderTotalReq) *dingo.ErrorWrap {
	day := 30
	sharedMode := "pcl"

	var (
		lst    []placeresp.PlaceUsedRateRankList
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)

	if param.SearchTime != "" {
		day, _ = strconv.Atoi(param.SearchTime)
	}
	if param.SharedMode != "" {
		sharedMode = param.SharedMode
	}

	//第一个版本
	//	sql := `SELECT a.place_id,p.place_name,a.orderTotal,p.device_count,a.turnover,
	//a.orderTotal/(p.device_count*?),
	//(a.turnover/a.orderTotal)/100 arpa from
	//(SELECT o.place_id,count(1) orderTotal,SUM(o.settlement_money) turnover FROM orders o WHERE  o.create_at >= ? and o.create_at <= ?  GROUP BY o.place_id) a
	//left JOIN places p on a.place_id = p.id  ORDER BY usageRate desc limit ?,?`

	//第二个版本
	//	sql := `SELECT a.place_id,p.place_name,a.orderTotal,p.device_count,a.turnover,
	//a.orderTotal/(p.device_count*?) as usageRate,
	//(a.turnover/a.orderTotal)/100 as arpa from
	//(SELECT o.place_id,count(1) orderTotal,SUM(o.settlement_money) turnover FROM orders o WHERE
	//date_sub(curdate(), interval ? day) <= DATE_FORMAT(FROM_UNIXTIME(o.create_at),'%Y-%m-%d') GROUP BY o.place_id) a
	//left JOIN places p on a.place_id = p.id  ORDER BY usageRate desc limit ?,?`

	//第三个版本
	//	sql := `SELECT a.place_id,p.place_name,a.orderTotal,p.device_count,a.turnover,
	//a.orderTotal/(p.device_count*?) as usageRate,
	//(a.turnover/a.orderTotal)/100 as arpa from
	//(SELECT o.place_id,count(1) orderTotal,SUM(o.settlement_money) turnover FROM orders o WHERE
	//shared_mode = ? and date_sub(curdate(), interval ? day) <= DATE_FORMAT(FROM_UNIXTIME(o.create_at),'%Y-%m-%d')
	//GROUP BY o.place_id order by orderTotal desc) a
	//left JOIN places p on a.place_id = p.id limit ?,?`

	//第四个版本
	//	sql := `select b.place_id,b.place_name,b.order_total,b.turnover/100 as turnover,b.usage_rate,b.arpa,c.device_count from
	//(SELECT a.place_id,p.place_name,a.order_total,p.device_count,a.turnover,
	//a.order_total/(p.device_count*?)*100 as usage_rate,
	//(a.turnover/a.order_total)/100 as arpa from
	//(SELECT o.place_id,count(1) order_total,SUM(o.settlement_money) turnover FROM orders o WHERE shared_mode = ? and
	//date_sub(curdate(), interval ? day) <= DATE_FORMAT(FROM_UNIXTIME(o.create_at),'%Y-%m-%d') GROUP BY o.place_id order by order_total desc) a
	//left JOIN places p on a.place_id = p.id) b
	//left join (select count(1) as device_count,place_id FROM devices WHERE shared_mode = ? GROUP BY place_id) c on b.place_id = c.place_id
	//order by ? limit ?,?`

	// 第五个版本
	// 1、订单表orders-获取网点最近30天的 订单数、订单总额  -- 得到表a
	// 2、网点表places 左联接关联 表a (所有网点信息对应的订单数) -- 得到表b
	// 3、设备表devices-获取网点的设备条数 -- 得到表 c
	// 4、计算使用率、客单价
	//    公式：使用率=订单数/(设备数*30天)
	//    公式：客单价=订单总额/订单数
	//	sql := `SELECT b.place_id,b.place_name,IFNULL(c.device_count,0) as device_count,
	//IFNULL(b.order_total,0) as order_total,IFNULL(b.turnover,0) as turnover,
	//IFNULL(b.order_total/(c.device_count*?)*100,0) as usage_rate,
	//IFNULL((b.turnover/b.order_total)/100,0) as arpa FROM
	//(
	//	SELECT p.id as place_id,p.place_name,a.order_total,a.turnover FROM places p
	//	LEFT JOIN (
	//		SELECT place_id,count(1) as order_total,IFNULL(SUM(o.settlement_money),0) as turnover FROM orders o
	//		WHERE shared_mode = ? and date_sub(curdate(), interval ? day) <= DATE_FORMAT(FROM_UNIXTIME(o.create_at),'%Y-%m-%d') GROUP BY place_id
	//	) a ON a.place_id = p.id
	//) b
	//LEFT JOIN (
	//	SELECT count(1) as device_count,place_id FROM devices where shared_mode = ? GROUP BY place_id
	//) c ON b.place_id = c.place_id
	//ORDER BY ?`

	//db := global.Orm.Raw(sql, day, sharedMode, day, sharedMode, sort, offset, limit).Find(&lst)
	//return dingo.ErrorIf(db.Error, lst)

	db := global.Orm
	orderSql := db.Table("orders").
		Select("place_id,count(1) as order_total,IFNULL(SUM(settlement_money),0) as turnover").
		Where("shared_mode = ?", sharedMode).
		Where("is_draw = ?", 0).
		Where("DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') >= date_sub(curdate(), interval ? day)", day+1).
		Where("DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') <= date_add(date_format(curdate(),'%Y-%m-%d'), interval -1 day)").
		Group("place_id")
	deviceSql := db.Table("devices").
		Select("count(1) as device_count,place_id").
		Where("shared_mode = ?", sharedMode).Group("place_id")

	dsql := db.Debug().Table("places p").
		Select("p.id as place_id,p.place_name,p.level,IFNULL(d.device_count,0) as device_count,"+
			"IFNULL(o.order_total,0) as order_total,IFNULL(o.turnover,0) as turnover,"+
			"IFNULL(o.turnover/100,0) as turnover_str,"+
			"IFNULL(o.order_total/(d.device_count*?)*100,0) as usage_rate,"+
			"IFNULL((o.turnover/o.order_total)/100,0) as arpa", day).
		Joins("LEFT JOIN (?) as o ON p.id = o.place_id", orderSql).
		Joins("LEFT JOIN (?) as d ON p.id = d.place_id", deviceSql)

	if param.SearchText != "" {
		dsql.Where("p.place_name like ?", fmt.Sprint("%", param.SearchText, "%"))
	}

	// 过滤
	if len(param.Level) > 0 {
		dsql.Where("p.level in (?)", param.Level)
	}
	//代理商
	if param.IsAdmin > helper.TypeNumIsAdminStaff { //当前账号登录是代理商或是合伙人
		// 获取某个用户下的所有代理商用户ID
		//placeModelLst := NewPlaceDao().GetPlaceByparentId(param.UserId).Unwrap().([]*placemodel.PlaceModel)
		//placeIdArr := make([]int, 0)
		////log.Println("placeModelLst 数组长度：", len(placeModelLst))
		//for _, placeModel := range placeModelLst {
		//	//fmt.Println("placeId: ",placeModel.Id)
		//	placeIdArr = append(placeIdArr, placeModel.Id)
		//}
		//log.Println("placeIdArr dao数组：", placeIdArr)
		userIdArr := NewUserDao().QueryChildUserIds(param.UserId).Unwrap().([]int)
		dsql.Where("p.agent_user_id in ?", userIdArr)
	}

	//分公司
	if param.IsPlace == helper.TypeNumIsAdminBranch {
		childUserIds := NewUserDao().QueryChildUserIds(param.UserId).Unwrap().([]int)
		placesIdArr := NewUserDao().GetPlacesIds(param.UserId, childUserIds).Unwrap().([]int)
		dsql.Where("p.id in ?", placesIdArr)
	}

	// 排序
	if param.SortField != "" && param.SortOrder == "ascend" {
		dsql.Order(fmt.Sprintf("%s asc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField != "" && param.SortOrder == "descend" {
		dsql.Order(fmt.Sprintf("%s desc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField == "" {
		dsql.Order("usage_rate desc")
	}

	dsql.Limit(limit).Offset(offset).Find(&lst).Offset(-1).Limit(-1).Count(&count)
	return dingo.ErrorIf(dsql.Error, lst, count)
}

func (d *OrderDao) GetOrderTotalAndCount(day int, sharedMode string, userId int, isAdmin uint8) *dingo.ErrorWrap {

	res := &struct {
		Total int64 `json:"total"`
		Count int64 `json:"count"`
	}{}
	db := global.Orm.Debug().Table("orders").
		Select("IFNULL(SUM(settlement_money),0) as total,count(1) as count").
		Where("shared_mode = ?", sharedMode).
		Where("DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') >= date_sub(curdate(), interval ? day)", day+1).
		Where("DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') <= date_add(date_format(curdate(),'%Y-%m-%d'), interval -1 day)").Find(&res)

	return dingo.ErrorIf(db.Error, res.Total, res.Count)
}

func (d *OrderDao) CountPlaceUsedRateList(param *request.OrderTotalReq) *dingo.ErrorWrap {
	day := 7
	sharedMode := "pcl"
	var count int64
	if param.SearchTime != "" {
		day, _ = strconv.Atoi(param.SearchTime)
	}
	if param.SharedMode != "" {
		sharedMode = param.SharedMode
	}

	//	sql := `SELECT count(1) as count,a.place_id,p.place_name,a.orderTotal,p.device_count,a.turnover,
	//a.orderTotal/(p.device_count*?) as usageRate,
	//(a.turnover/a.orderTotal)/100 as arpa from
	//(SELECT o.place_id,count(1) orderTotal,SUM(o.settlement_money) turnover FROM orders o WHERE
	//date_sub(curdate(), interval ? day) <= DATE_FORMAT(FROM_UNIXTIME(o.create_at),'%Y-%m-%d') GROUP BY o.place_id) a
	//left JOIN places p on a.place_id = p.id  ORDER BY usageRate desc`

	sql := `select count(1) as count from
(SELECT a.place_id,p.place_name,a.order_total,p.device_count,a.turnover/100 as turnover,
a.order_total/(p.device_count*?)*100 as usage_rate,
(a.turnover/a.order_total)/100 as arpa from
(SELECT o.place_id,count(1) order_total,SUM(o.settlement_money) turnover FROM orders o WHERE shared_mode = ? and
date_sub(curdate(), interval ? day) <= DATE_FORMAT(FROM_UNIXTIME(o.end_at),'%Y-%m-%d') GROUP BY o.place_id order by order_total desc) a
left JOIN places p on a.place_id = p.id) b
left join (select count(1) as device_count,place_id FROM devices WHERE shared_mode = ? GROUP BY place_id) c on b.place_id = c.place_id`

	db := global.Orm.Raw(sql, day, sharedMode, day, sharedMode).Find(&count)
	return dingo.ErrorIf(db.Error, count)
}

// 统计每个商户的每天的订单量和总收益
func (d *OrderDao) GetOrdersStatistics(currDate string) *dingo.ErrorWrap {
	var (
		lst []*ordersstatistics.OrdersstatisticsModel
	)

	db := global.Orm.Debug().Table("orders o").
		Select("count( 1 ) AS order_count,IFNULL(SUM(o.settlement_money),0) AS settlement_money,o.shared_mode,o.place_id").
		Where("o.state = 5 AND o.is_draw = 0").
		Where("o.place_id IN ( SELECT id FROM places p WHERE p.is_delete = 0 )").
		Where(" DATE_FORMAT(FROM_UNIXTIME(o.end_at),'%Y%m%d') = ?", currDate).
		Group("o.place_id,o.shared_mode").
		Find(&lst)

	return dingo.ErrorIf(db.Error, lst)
}

// 统计每个商户的每天的收益(分成后)
func (d *OrderDao) GetPlaceIncomeCount(userId int, currDate string, sharedMode string) *dingo.ErrorWrap {
	var income int64
	db := global.Orm.Debug().Table("dividends_log ").
		Select("IFNULL(SUM(money),0) AS income").
		//Where("state = 5").
		Where("user_id = ?", userId).
		Where("shared_mode = ?", sharedMode).
		Where(" DATE_FORMAT(FROM_UNIXTIME(settlement_at),'%Y%m%d') = ?", currDate).
		Find(&income)

	return dingo.ErrorIf(db.Error, income)
}

// 新增
func (d *OrderDao) InsertOrdersStatistics(m *ordersstatistics.OrdersstatisticsModel) *dingo.ErrorWrap {
	db := global.Orm.Debug().Table("orders_statistics").Create(m)
	return dingo.ErrorIf(db.Error, true)
}

// 修改
func (d *OrderDao) UpdateOrdersStatistics(m *ordersstatistics.OrdersstatisticsModel) *dingo.ErrorWrap {
	currDate := time.Unix(int64(m.CreateAt), 0).Format("20060102")
	db := global.Orm.Debug().Table("orders_statistics").
		Where("place_id = ?", m.PlaceId).
		Where("DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y%m%d') = ?", currDate).
		Where("shared_mode = ?", m.SharedMode).
		Model(&m).Updates(m)
	return dingo.ErrorIf(db.Error, true)
}

// 查询
func (d *OrderDao) GetOrdersStatisticsByPlaceIdTime(info *ordersstatistics.OrdersstatisticsModel, currDate string) *dingo.ErrorWrap {

	m := ordersstatistics.New()

	//currDate := time.Unix(int64(info.CreateAt), 0).Format("20060102")
	//log.Println("11111: ",info.CreateAt,currDate)

	db := global.Orm.Debug().Raw("select * from orders_statistics where place_id = ? "+
		" and DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y%m%d') = ? and "+
		" shared_mode = ?", info.PlaceId, currDate, info.SharedMode).
		Find(&m)
	return dingo.ErrorIf(db.Error, m)

}

// 按天查询商户交易、订单详情
func (d *OrderDao) GetOrdersStatisticsDayList(param *request.OrdersstaListReq) *dingo.ErrorWrap {

	var (
		lst    []*ordersstatistics.OrdersstatisticsModel
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)

	db := global.Orm.Debug().Table("place_income").Select("income_day ,device_total,settlement_money,order_count")

	if param.PlaceId > 0 {
		db.Where("place_id = ?", param.PlaceId)
	}

	if param.SharedMode != "" {
		db.Where("shared_mode = ?", param.SharedMode)
	}
	// 时间查询
	if param.SerachTime != "" {
		serachTime := strings.Split(param.SerachTime, ",")
		db.Where("income_day >= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", serachTime[0])
		db.Where("income_day <= DATE_FORMAT(FROM_UNIXTIME(?),'%Y-%m-%d')", serachTime[1])
	}

	db.Order("income_day desc")
	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)

	return dingo.ErrorIf(db.Error, lst, count)

}

// 公众号 - 获取代理商下级商户收益排行
func (d *OrderDao) GetPlaceIncomeRankByAgent(param *request.PlaceIncomeRankByAgent, userId int, IsAdmin, IsPlace uint8) *dingo.ErrorWrap {

	var (
		lst    []*ordersstatistics.PlaceIncomeByDay
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)

	db := global.Orm.Debug().Table("dividends_log").Select("SUM(money) as total,place_name,place_id")

	var placesIdArr []int
	if IsAdmin != helper.TypeNumIsAdminOperator {
		userIdArr := NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
		placesIdArr = NewUserDao().GetPlacesIds(userId, userIdArr).Unwrap().([]int)
		//db.Where("place_id in ?", placesIdArr)
	}
	db.Where("user_id = ?", userId)

	db.Group("place_id").Order("total DESC")

	//db.Order("create_at desc")

	db.Limit(limit).Offset(offset).Find(&lst)

	if IsAdmin != helper.TypeNumIsAdminOperator {
		countSQL := `SELECT count(1) FROM (SELECT * FROM place_income WHERE place_id in (?) GROUP BY place_id) a`
		global.Orm.Debug().Raw(countSQL, placesIdArr).Count(&count)
	} else {
		countSQL := `SELECT count(1) FROM (SELECT * FROM place_income WHERE 1 GROUP BY place_id) a`
		global.Orm.Debug().Raw(countSQL).Count(&count)
	}

	return dingo.ErrorIf(db.Error, lst, count)
}

// 按月显示商户收益信息
func (d *OrderDao) GetOrdersStatisticsMonthList(param *request.OrdersstaListReq) *dingo.ErrorWrap {

	lst := make([]*ordersstatistics.OrdersstatisticsModel, 0)

	db := global.Orm.Debug().Table("orders_statistics").
		Select("place_id,DATE_FORMAT( FROM_UNIXTIME( create_at ), '%Y%m' ) AS dayMonth," +
			" IFNULL(SUM(settlement_money),0) AS settlement_money,IFNULL(SUM(income),0) AS income,IFNULL(SUM(order_count),0) AS order_count")

	if param.PlaceId > 0 {
		db.Where("place_id = ?", param.PlaceId)
	}

	if param.SharedMode != "" {
		db.Where("shared_mode = ?", param.SharedMode)
	}
	db.Group("DATE_FORMAT( FROM_UNIXTIME( create_at ), '%Y%m' )")
	db.Order("create_at desc").Find(&lst)

	return dingo.ErrorIf(db.Error, lst)

}

// 按月显示商户收益信息
func (d *OrderDao) GetPlaceAllIncome(placeId int, sharedMode string) *dingo.ErrorWrap {

	var income int64

	db := global.Orm.Debug().Table("orders_statistics").
		Select("IFNULL(SUM(income),0) AS income")

	if placeId > 0 {
		db.Where("place_id = ?", placeId)
	}

	if sharedMode != "" {
		db.Where("shared_mode = ?", sharedMode)
	}
	db.Find(&income)

	return dingo.ErrorIf(db.Error, income)
}

// -------------代理商层级操作

// 查询下级包括本身某一天的销售额
func (d *OrderDao) QueryChildTodayTotalMoney(t string, userId []int) *dingo.ErrorWrap {
	var total int64
	//	sql := `SELECT SUM(settlement_money) as total from (SELECT money,settlement_money,DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') AS days, trade_no, place_name, user_name ,place_id, user_id
	//FROM orders WHERE DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = DATE_FORMAT(CURRENT_DATE(), '%Y-%m-%d') GROUP BY create_at desc) as a`
	//	sql := `SELECT IFNULL(SUM(settlement_money),0) as total from
	//(SELECT money,settlement_money FROM orders WHERE DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = ? GROUP BY create_at desc) as a`
	sql := `SELECT IFNULL( SUM( settlement_money ), 0 ) AS total FROM orders 
			WHERE state = 5 and agent_user_id in (?) and DATE_FORMAT( FROM_UNIXTIME( end_at ), '%Y-%m-%d' ) = ?`

	db := global.Orm.Raw(sql, userId, t).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

// 获取周销售额
func (d *OrderDao) GetWeekTotalMoneyChild(i int, userId []int) *dingo.ErrorWrap {
	var total int64
	//	sql := `SELECT IFNULL(SUM(settlement_money),0) as total from
	//(SELECT money,settlement_money,DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') AS days,
	//YEARWEEK(DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d'),1) as weeks FROM orders WHERE
	//YEARWEEK(DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d'),1) = YEARWEEK(now(),1)-?) as a`

	// modify by boyka on 20210407 将上面SQL简化，如果有问题及时联系
	sql := `SELECT IFNULL(SUM(settlement_money),0) as total FROM orders WHERE 
			YEARWEEK(DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d'),1) = YEARWEEK(now(),1)-? and agent_user_id in (?)`

	db := global.Orm.Raw(sql, i, userId).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

// 获取总金额
func (d *OrderDao) GetTotalMoneyChild(userId []int) *dingo.ErrorWrap {
	total := &struct {
		Total int64
		Count int64
	}{}
	sql := `SELECT IFNULL(SUM(settlement_money),0) as total,count(1) as count FROM orders WHERE state = 5 and agent_user_id in (?)`
	db := global.Orm.Raw(sql, userId).Find(&total)
	return dingo.ErrorIf(db.Error, total.Total, total.Count)
}

// 获取某一天的销售订单笔数
func (d *OrderDao) GetTodayOrderCountChild(t string, userIds []int) *dingo.ErrorWrap {
	var count int64
	sql := `SELECT count(*) as count from 
(SELECT money,settlement_money FROM orders WHERE DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = ? AND agent_user_id in (?) GROUP BY end_at ) as a`
	db := global.Orm.Raw(sql, t, userIds).Find(&count)
	return dingo.ErrorIf(db.Error, count)
}

// 获取近几天的交易笔数
func (d *OrderDao) GetLastDayOrderCountChild(i int, userIds []int) *dingo.ErrorWrap {
	var lst []*resphelper.ChartListResp
	sql := `SELECT count(1) as y,DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') AS x
FROM orders WHERE state = 5 and agent_user_id in (?) and
date_sub(curdate(), interval ? day) <= DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d')
GROUP BY DATE_FORMAT(FROM_UNIXTIME(end_at), '%Y-%m-%d') asc`
	db := global.Orm.Raw(sql, userIds, i).Find(&lst)
	return dingo.ErrorIf(db.Error, lst)
}

//----------------经营分析分公司操作
func (d *OrderDao) QueryPlacesTodayTotalMoney(t string, placesIds []int) *dingo.ErrorWrap {
	var total int64
	//	sql := `SELECT SUM(settlement_money) as total from (SELECT money,settlement_money,DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') AS days, trade_no, place_name, user_name ,place_id, user_id
	//FROM orders WHERE DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = DATE_FORMAT(CURRENT_DATE(), '%Y-%m-%d') GROUP BY create_at desc) as a`
	//	sql := `SELECT IFNULL(SUM(settlement_money),0) as total from
	//(SELECT money,settlement_money FROM orders WHERE DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = ? GROUP BY create_at desc) as a`
	sql := `SELECT IFNULL( SUM( settlement_money ), 0 ) AS total FROM orders 
			WHERE state = 5 and place_id in (?) and DATE_FORMAT( FROM_UNIXTIME( end_at ), '%Y-%m-%d' ) = ?`

	db := global.Orm.Raw(sql, placesIds, t).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

// 获取周销售额
func (d *OrderDao) GetWeekTotalMoneyPlaces(i int, placesIds []int) *dingo.ErrorWrap {
	var total int64
	//	sql := `SELECT IFNULL(SUM(settlement_money),0) as total from
	//(SELECT money,settlement_money,DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') AS days,
	//YEARWEEK(DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d'),1) as weeks FROM orders WHERE
	//YEARWEEK(DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d'),1) = YEARWEEK(now(),1)-?) as a`

	// modify by boyka on 20210407 将上面SQL简化，如果有问题及时联系
	sql := `SELECT IFNULL(SUM(settlement_money),0) as total FROM orders WHERE 
			YEARWEEK(DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d'),1) = YEARWEEK(now(),1)-? and place_id in (?)`

	db := global.Orm.Raw(sql, i, placesIds).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

// 获取总金额
func (d *OrderDao) GetTotalMoneyPlaces(placesIds []int) *dingo.ErrorWrap {
	total := &struct {
		Total int64
		Count int64
	}{}
	sql := `SELECT IFNULL(SUM(settlement_money),0) as total,count(1) as count FROM orders WHERE state = 5 and place_id in (?)`
	db := global.Orm.Raw(sql, placesIds).Find(&total)
	return dingo.ErrorIf(db.Error, total.Total, total.Count)
}

// 获取某一天的销售订单笔数
func (d *OrderDao) GetTodayOrderCountPlaces(t string, placesIds []int) *dingo.ErrorWrap {
	var count int64
	sql := `SELECT count(*) as count from 
(SELECT money,settlement_money FROM orders WHERE DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = ? AND place_id in (?) GROUP BY end_at) as a`
	db := global.Orm.Raw(sql, t, placesIds).Find(&count)
	return dingo.ErrorIf(db.Error, count)
}

// 获取近几天的交易笔数
func (d *OrderDao) GetLastDayOrderCountPlaces(i int, placesIds []int) *dingo.ErrorWrap {
	var lst []*resphelper.ChartListResp
	sql := `SELECT count(1) as y,DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') AS x
FROM orders WHERE state = 5 and place_id in (?) and
date_sub(curdate(), interval ? day) <= DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d')
GROUP BY DATE_FORMAT(FROM_UNIXTIME(end_at), '%Y-%m-%d') asc`
	db := global.Orm.Raw(sql, placesIds, i).Find(&lst)
	return dingo.ErrorIf(db.Error, lst)
}

// 扫码量
func (d *OrderDao) GetPlaceOrderScanCountByPlaceId(placeId int, timeStamp int64) *dingo.ErrorWrap {
	t := time.Unix(timeStamp, 0)
	dateStr := t.Format("2006-01-02")

	var count int64
	sql := `SELECT count(*) as count from orders where is_draw = 0 and place_id = ? and DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = ?`
	db := global.Orm.Raw(sql, placeId, dateStr).Find(&count)
	return dingo.ErrorIf(db.Error, count)
}

// 获取商户有产设备条数
func (d *OrderDao) GetActiveDevCount(placeId int, timeStamp string) *dingo.ErrorWrap {
	//t := time.Unix(timeStamp, 0)
	//dateStr := t.Format("2006-01-02")
	var total int64
	sql := `select count(*) from 
(SELECT device_sn as total FROM orders where is_draw = 0 and place_id = ? and DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = ? group by device_sn) as a`
	db := global.Orm.Debug().Raw(sql, placeId, timeStamp).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

//查询网点和用户ID
func (d *OrderDao) GetPlaceIdAndUserId(tradeNo string) *dingo.ErrorWrap {
	placeInfo := placeresp.PlaceIdAndUserId{}

	sql := `SELECT
		p.id AS place_id,
		p.user_id,
		date,
		settlement_money,
		complete_count,
		cancel_count,
		dl_money
	FROM
		places p
		LEFT JOIN (
	SELECT
		o.place_id,
		DATE_FORMAT( FROM_UNIXTIME( o.end_at ), '%Y-%m-%d' ) AS date,
		o.settlement_money  AS settlement_money,
		dl_money
	FROM
		orders o
		LEFT JOIN (SELECT money as dl_money,trade_no,user_id  FROM dividends_log  ) dl ON dl.trade_no = o.trade_no and dl.user_id = o.user_id
	WHERE
		o.trade_no = ?
		AND o.state = 5
		AND is_draw != 1
		) o ON o.place_id = p.id
		LEFT JOIN(
		SELECT complete_count,cancel_count,place_id,income_day FROM place_income
		) pi ON pi.place_id = p.id and pi.income_day = date
	
		WHERE date is not null`

	//sql := `select id ,user_id  FROM places WHERE id in(SELECT place_id FROM orders WHERE trade_no = ?)`
	db := global.Orm.Debug().Raw(sql, tradeNo).Find(&placeInfo)
	return dingo.ErrorIf(db.Error, placeInfo)

}

func (d *OrderDao) GetPlaceIncomeByPlaceId(placeId int, date string) *dingo.ErrorWrap {
	placeIncomeModel := placeincome.PlaceIncomeModel{}
	db := global.Orm.Debug().Table("place_income").Where("place_id = ? and income_day = ?", placeId, date).Find(&placeIncomeModel)
	return dingo.ErrorIf(db.Error, placeIncomeModel)
}

func (d *OrderDao) UpdatePlaceStatistical(m *placeresp.PlaceIdAndUserId) *dingo.ErrorWrap {
	db := global.Orm.Debug().Table("place_income").Select("cancel_count", "complete_count", "income", "settlement_money").Where("income_day =? and place_id = ?", m.Date, m.PlaceId).Model(m).Updates(&m)
	return dingo.ErrorIf(db.Error, true)
}

//查询代理商统计参数
func (d *OrderDao) GetAgentStatisticalByTradeNo(tradeNo string) *dingo.ErrorWrap {
	var agentStatisticalInfo []placeresp.PlaceIdAndUserId
	sql := `	SELECT
	p.id AS place_id,
	dl_user_id,
	date,
	settlement_money,
	complete_count,
	cancel_count,
	br_complete_count,
	br_cancel_count,
	dl_money 
FROM
	places p
	LEFT JOIN (
SELECT
	o.place_id,
	DATE_FORMAT( FROM_UNIXTIME( o.end_at ), '%Y-%m-%d' ) AS date,
	o.settlement_money  AS settlement_money,
	dl_user_id,
	dl_money
FROM
	orders o
	LEFT JOIN (SELECT money as dl_money,trade_no,user_id as dl_user_id FROM dividends_log  ) dl ON dl.trade_no = o.trade_no  
WHERE
	o.trade_no = ?
	AND o.state = 5
	AND is_draw != 1
	GROUP BY dl_user_id
	) o ON o.place_id = p.id  
	
	LEFT JOIN(
	SELECT complete_count,cancel_count,agent_user_id,income_day FROM agent_income 
	) ag ON ag.agent_user_id = dl_user_id and ag.income_day = date
	
		LEFT JOIN(
	SELECT complete_count as br_complete_count,cancel_count as br_cancel_count,agent_user_id as branch_user_id ,income_day FROM branch_income 
	) br ON br.branch_user_id = dl_user_id and br.income_day = date
	
	WHERE date is not null `
	db := global.Orm.Debug().Raw(sql, tradeNo).Find(&agentStatisticalInfo)
	return dingo.ErrorIf(db.Error, agentStatisticalInfo)
}

func (d *OrderDao) GetAgentIncomeByPlaceId(userId int, date string) *dingo.ErrorWrap {
	agentIncomeModel := agentincome.AgentIncomeModel{}
	db := global.Orm.Debug().Table("agent_income").Where("agent_user_id = ? and income_day = ?", userId, date).Find(&agentIncomeModel)
	return dingo.ErrorIf(db.Error, agentIncomeModel)
}

func (d *OrderDao) UpdateAgentStatistical(m *placeresp.PlaceIdAndUserId) *dingo.ErrorWrap {
	db := global.Orm.Debug().Table("agent_income").Select("cancel_count", "complete_count", "total_money", "trade_total", "divinds_money").Where("income_day =? and agent_user_id = ?", m.Date, m.DlUserId).Model(m).Updates(&m)
	return dingo.ErrorIf(db.Error, true)
}

func (d *OrderDao) GetBranchIncomeByPlaceId(userId int, date string) *dingo.ErrorWrap {
	agentIncomeModel := agentincome.AgentIncomeModel{}
	db := global.Orm.Debug().Table("branch_income").Where("agent_user_id = ? and income_day = ?", userId, date).Find(&agentIncomeModel)
	return dingo.ErrorIf(db.Error, agentIncomeModel)
}

func (d *OrderDao) UpdateBranchStatistical(m *placeresp.BranchIncomeStatistical) *dingo.ErrorWrap {
	db := global.Orm.Debug().Table("branch_income").Select("cancel_count", "complete_count", "total_money", "trade_total", "divinds_money").Where("income_day =? and agent_user_id = ?", m.Date, m.UserId).Model(m).Updates(&m)
	return dingo.ErrorIf(db.Error, true)
}

//H5收益统计
func (d *OrderDao) GetEarningsStatisticalList(sharedMode, timeRange string, isAdmin uint8, userId int, isPlace uint8) *dingo.ErrorWrap {
	if sharedMode == "" {
		sharedMode = "pcl"
	}

	var lst []*resphelper.ChartListResp

	db := global.Orm.Debug().Table("dividends_log").
		Select("IFNULL( SUM( money ), 0 ) AS y,DATE_FORMAT( FROM_UNIXTIME( create_at ), '%Y-%m-%d' ) AS x ").
		Where("shared_mode = ? ", sharedMode).
		Where("DATE_FORMAT( FROM_UNIXTIME( create_at ), '%Y-%m-%d' ) >= date_sub( curdate(), INTERVAL 31 DAY ) ").
		Where("DATE_FORMAT( FROM_UNIXTIME( create_at ), '%Y-%m-%d' ) <= date_format( curdate(), '%Y-%m-%d' )").
		Where("state = 5")

	if userId > 0 {
		db.Where(" user_id = ? ", userId)
	}

	db.Group("DATE_FORMAT( FROM_UNIXTIME( create_at ), '%Y-%m-%d' ) ASC").Find(&lst)
	return dingo.ErrorIf(db.Error, lst)
}

//H5今日收益
func (d *OrderDao) GetEarningsIncome(userId int, sharedMode string) *dingo.ErrorWrap {
	if sharedMode == "" {
		sharedMode = "pcl"
	}
	var total int64
	sql := `SELECT IFNULL(SUM(money),0) as total FROM dividends_log WHERE user_id = ? and
	DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = date_format( curdate(), '%Y-%m-%d' )   and shared_mode = ? and is_tianhai = 0`

	db := global.Orm.Raw(sql, userId, sharedMode).Find(&total)
	return dingo.ErrorIf(db.Error, total)
}

//查询设备总数
func (d *OrderDao) GetMattersCountDevice(placeIds []int, userId int) *dingo.ErrorWrap {
	var deviceCount int64
	if len(placeIds) == 0 {
		return dingo.ErrorIf(nil, deviceCount)
	}

	db := global.Orm
	//查询设备总数
	if userId == 2 {
		sql := `select count(1) from devices`
		db.Debug().Raw(sql).Find(&deviceCount)
	} else {
		sql := `select count(1) from devices where place_id in (?) `
		db.Debug().Raw(sql, placeIds).Find(&deviceCount)

	}
	return dingo.ErrorIf(db.Error, deviceCount)
}

// GetActiveCountPlaceDevice 查询设备/网点动销数
func (d *OrderDao) GetActiveCountPlaceDevice(userId int, inDay string) *dingo.ErrorWrap {
	dbInfo := &request.GetActiveCountPlaceDeviceReq{}

	sql := `SELECT IFNULL(SUM(d_num),0)device_num, COUNT(1)place_num FROM (SELECT COUNT(1)d_num, o1.place_id FROM (
	SELECT o.device_sn,o.place_id FROM orders o LEFT JOIN orders_user_relevancy our ON o.id=our.id WHERE 
	our.user_id=? AND our.end_date=? AND o.is_draw<>? GROUP BY o.device_sn) o1 GROUP BY o1.place_id) o2`
	db := global.Orm.Raw(sql, userId, inDay, helper.TypeNumCommonStatusTrue).Find(&dbInfo)

	return dingo.ErrorIf(db.Error, dbInfo)
}

//查询设备使用率
func (d *OrderDao) GetMattersDeviceUse(placeIds []int, isDraw int) *dingo.ErrorWrap {
	var isDrawSql string
	if isDraw == 1 {
		isDrawSql = ` is_draw = 1`
	} else {
		isDrawSql = ` is_draw != 1 `
	}

	//查询设备使用率
	var useDeviceTotal int64
	sql := `select count(*) from 
(SELECT device_sn as total FROM orders where ` + isDrawSql + ` and place_id  in (?) and DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') = date_format( curdate(), '%Y-%m-%d' ) group by device_sn) as a`
	db := global.Orm.Debug().Raw(sql, placeIds).Find(&useDeviceTotal)
	return dingo.ErrorIf(db.Error, useDeviceTotal)

}

//查询今日订单数
func (d *OrderDao) GetMattersOrderCount(placeIds []int, isDraw, userId int) *dingo.ErrorWrap {
	var orderCount int64
	var isDrawSql string
	db := global.Orm
	if isDraw == 1 {
		isDrawSql = ` AND is_draw = 1`
	} else {
		isDrawSql = ` AND is_draw != 1 `
	}

	if userId == 2 {
		sql := `SELECT count(1) as total FROM orders WHERE 
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = date_format( curdate(), '%Y-%m-%d' ) and state = 5  ` + isDrawSql + ` and shared_mode = 'pcl'  and is_tianhai = 0 `
		db.Raw(sql).Find(&orderCount)
	} else {
		sql := `SELECT count(1) as total FROM orders WHERE place_id in(?) and 
DATE_FORMAT(FROM_UNIXTIME(end_at),'%Y-%m-%d') = date_format( curdate(), '%Y-%m-%d' ) and state = 5  ` + isDrawSql + ` and shared_mode = 'pcl'  and is_tianhai = 0 `
		db.Raw(sql, placeIds).Find(&orderCount)
	}

	return dingo.ErrorIf(db.Error, orderCount)
}

//网点使用率
func (d *OrderDao) GetMattersPlaceUse(placeIds []int, userId int) *dingo.ErrorWrap {
	var placeCount int64
	db := global.Orm
	if userId == 2 {
		sql := ` SELECT count(1) AS total FROM places where  active_status = 1 `
		db.Raw(sql, placeIds).Find(&placeCount)
	} else {
		sql := ` SELECT count(1) AS total FROM places where  id  in (?) and active_status = 1 `
		db.Raw(sql, placeIds).Find(&placeCount)
	}

	return dingo.ErrorIf(db.Error, placeCount)
}

func (d *OrderDao) GetUserPlaceCount() *dingo.ErrorWrap {
	var placeCount int64
	sql := ` SELECT count(1) AS total FROM places `
	db := global.Orm.Raw(sql).Find(&placeCount)
	return dingo.ErrorIf(db.Error, placeCount)
}

// 开始计费时间更新
func (d *OrderDao) UpdateBeginAtOrder(orderId, second int) *dingo.ErrorWrap {
	//sql := `UPDATE orders SET begin_at=IF(begin_at=0,pay_at+?,begin_at+?) WHERE id=? AND (?+begin_at-pay_at)<2500`
	//db := global.Orm.Debug().Exec(sql, second, second, orderId, second)
	sql := `UPDATE orders SET begin_at = begin_at + ? WHERE id = ?`
	db := global.Orm.Debug().Exec(sql, second, orderId)
	return dingo.ErrorIf(db.Error)
}
